<script setup>
import { dayjs, ElMessage } from 'element-plus'
import * as htmlparser2 from 'htmlparser2'

import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
import { ref, onMounted, reactive } from 'vue'
dayjs.extend(utc)
dayjs.extend(duration)

let electron = null
if (window.electron) {
  electron = window.electron
}

let columns = ref([])
let tableData = ref([])
let loading = ref(false)

let sharurl = ref('')
// let userHtml = ref('')
let nowhandle = ref('')

columns.value.push(
  ...[
    {
      align: 'center',
      show: true,
      width: '200',
      fixed: false,
      prop: 'home',
      label: '主播的个人主页地址'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'infostr',
      label: '个人信息'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'nickname',
      label: '主播的昵称'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'user_id',
      label: '主播的ID'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'room_id',
      label: '直播间Id'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'live_status',
      label: '直播状态'
    },
    {
      align: 'center',
      show: true,
      fixed: false,
      prop: 'sec_user_id',
      label: '主播的加密ID'
    },
    {
      align: 'center',
      show: true,
      width: '300',
      fixed: false,
      prop: 'operation',
      label: '操作'
    }
  ]
)

onMounted(async () => {
  // if (electron) {
  //   electron.ipcRenderer.on('dyuser', (event, data) => {
  //     // console.warn(data)
  //     try {
  //       let info = JSON.parse(data)
  //       if (info['err_msg']) {
  //         ElMessage({
  //           type: 'error',
  //           message: info['err_msg']
  //         })
  //       }
  //     } catch (error) {
  //       // const dh = new htmlparser2.DomHandler((err, dom) => {
  //       //   const e = htmlparser2.DomUtils.getElementsByTagName('div', dom)
  //       //   for (const iterator of e) {
  //       //     console.warn(htmlparser2.DomUtils.innerText(iterator))
  //       //   }
  //       // })
  //       let flags_ = false
  //       let flags_number = 0
  //       let infostr = []
  //       const parser = new htmlparser2.Parser(
  //         {
  //           onattribute(name, value) {
  //             if (name == 'img' && value == 'PbpHcHqa') {
  //               console.warn(name, value)
  //             }
  //           },
  //           onopentag(name, attribs) {
  //             if (name == 'a' && 'B3AsdZT9' == attribs.class) {
  //               try {
  //                 let parms = new URL(attribs.href)
  //                 let room_id = parms.searchParams.get('room_id')
  //                 if (room_id) {
  //                   console.warn(room_id)
  //                   ElMessage({
  //                     type: 'success',
  //                     message: `该用户正在直播中${room_id}`
  //                   })
  //                   let tmp = []
  //                   for (let index = 0; index < tableData.value.length; index++) {
  //                     const element = tableData.value[index]
  //                     if (element.sec_user_id == nowhandle.value) {
  //                       element['room_id'] = room_id
  //                       element['live_status'] = 2
  //                       element['live_url'] = attribs.href
  //                     }
  //                     tmp.push(element)
  //                   }
  //                   tableData.value = tmp
  //                   localStorage.setItem('TaskPreparation', JSON.stringify(tableData.value))
  //                 }
  //               } catch (error) {
  //                 console.warn(error)
  //                 ElMessage({
  //                   type: 'error',
  //                   message: `该用户尚未直播`
  //                 })
  //               }
  //             }
  //             if (name == 'img' && 'jZ9bChTp' == attribs.class) {
  //               console.warn(attribs.src)
  //             }
  //           },
  //           ontext(text) {
  //             if (text == '直播中') {
  //               console.warn(text)
  //             }
  //             if (text == '直播已结束') {
  //               console.warn(text)
  //             }
  //             if (flags_ && flags_number <= 13) {
  //               ++flags_number
  //               infostr.push(text)
  //             }
  //             if (text == '换肤') {
  //               flags_ = true
  //             }
  //           }
  //         },
  //         {
  //           recognizeCDATA: true
  //         }
  //       )
  //       parser.parseComplete(data)
  //       if (infostr.length > 0) {
  //         let tmp = []
  //         for (let index = 0; index < tableData.value.length; index++) {
  //           const element = tableData.value[index]
  //           if (element.sec_user_id == nowhandle.value) {
  //             element['nickname'] = infostr[0]
  //             element['infostr'] = infostr.join(';')
  //           }
  //           tmp.push(element)
  //         }
  //         tableData.value = tmp
  //         localStorage.setItem('TaskPreparation', JSON.stringify(tableData.value))
  //       }
  //       // console.warn(error)
  //     }
  //   })
  // }
  //查看预开始任务缓存
  let Preparation = localStorage.getItem('TaskPreparation')
  if (Preparation) {
    tableData.value = JSON.parse(Preparation)
  } else {
    tableData.value = []
  }
})

async function primaryLook(item) {
  try {
    if (item) {
      nowhandle.value = item.sec_uid
      sharurl.value = item.home
    } else {
      nowhandle.value = ''
      if (!sharurl.value) {
        ElMessage({
          type: 'error',
          message: '请输入抖音个人首页链接!'
        })
        return
      }
    }
    if (!item) {
      for (let index = 0; index < tableData.value.length; index++) {
        const element = tableData.value[index]
        if (element.home == sharurl.value) {
          ElMessage({
            type: 'error',
            message: '该预开始任务已添加!'
          })
          throw '该预开始任务已添加!'
        }
      }
    }

    try {
      new URL(sharurl.value)
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '链接不合法!'
      })
      throw '链接不合法!'
    }
    // 回收设备
    let response_ = await fetch(sharurl.value, {
      method: 'GET',
      body: undefined
    })
    let URL_ = new URL(response_.url)
    let obj = {}
    for (const iterator of URL_.searchParams) {
      obj[iterator[0]] = iterator[1]
    }
    console.warn(obj)
    if (obj['ecom_share_track_params']) {
      if (JSON.parse(obj['ecom_share_track_params'])['enter_from'] == 'live') {
        ElMessage({
          type: 'error',
          message: '该链接非用户首页链接'
        })
        throw '该链接非用户首页链接!'
      }
    }
    if (obj['liveId']) {
      ElMessage({
        type: 'error',
        message: '该链接非用户首页链接!'
      })
      throw '该链接非用户首页链接!'
    }
    electron.ipcRenderer.send('dyuser', `https://www.douyin.com/user/${obj.sec_uid || ''}`)

    nowhandle.value = obj.sec_uid
    if (!item) {
      tableData.value.push({
        home: sharurl.value,
        nickname: '',
        user_id: '',
        room_id: '',
        sec_user_id: obj.sec_uid,
        live_status: 1
      })
      localStorage.setItem('TaskPreparation', JSON.stringify(tableData.value))
    }
  } catch (error) {
    console.warn()
  }
}
async function _blank_page(url) {
  if (electron) {
    electron.ipcRenderer.send('_blank_page', url)
  }
}
//清除缓存数据
async function clearPrimaryLook() {
  tableData.value = []
  localStorage.removeItem('TaskPreparation')
}

let title = ref('')
let url = ref('')
let duration2 = ref('')
let count = ref('')
let nickname = ref('')

/**
 *
 * 添加任务
 *
 */
let centerDialogVisible = ref(false)
let slecteInfo = null
async function DialogVisible(item) {
  slecteInfo = null
  if (item.live_status == 1) {
    ElMessage({
      type: 'error',
      message: '该预开始任务未在直播中!'
    })
    return
  }
  slecteInfo = item
  console.warn(JSON.stringify(item))
  let _url = new URL(slecteInfo.live_url)
  url.value = _url.origin + _url.pathname
  nickname.value = item.infostr ? item.infostr.split(';')[1] : '' //主播昵称
  centerDialogVisible.value = true
}

async function addYinTask() {
  if (!slecteInfo) {
    ElMessage({
      type: 'error',
      message: '添加错误!,请重试'
    })
    return
  }

  let userInfo = localStorage.getItem('userinfo')
  // 添加任务
  let response_ = await fetch(`http://208.87.207.213:38390/DouYinTask/DouYinTaskadd`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify({
      account_id: JSON.parse(userInfo).id,
      task_name: title.value, //任务标题
      room_id: slecteInfo.room_id, //房间ID
      user_id: '未知', //用户ID
      sec_user_id: slecteInfo.sec_user_id, //加密用户ID
      nickname: nickname.value, //主播昵称
      duration: duration2.value, //时长
      number: count.value, //数量
      remarks: '直播任务',
      list: '[]',
      live_url: url.value /* 直播链接 */
    })
  })
  let response = await response_.json()
  if (response.code !== 200) {
    ElMessage({
      type: 'error',
      message: response.msg || '添加失败，请检查数据'
    })
    return
  }
  ElMessage({
    type: 'success',
    message: `添加任务成功！`
  })
  centerDialogVisible.value = false
}
//移除
async function removePreparation(index) {
  tableData.value.splice(index, 1)
  localStorage.setItem('TaskPreparation', JSON.stringify(tableData.value))
}
</script>

<template>
  <div class="container no-drag">
    <div style="padding: 20px; width: 200px">
      <span style="margin-top: 20px">输入抖音个人首页链接:</span>
      <el-input v-model="sharurl"></el-input>
    </div>
    <el-button type="primary" style="margin-left: 20px" @click="primaryLook(false)"
      >添加预开始任务</el-button
    >
    <el-button type="danger" style="margin-left: 20px" @click="clearPrimaryLook"
      >清除预开始任务</el-button
    >
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      row-key="id"
      size="large"
      stripe
      style="width: 100%; margin-top: 20px"
      height="200"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :fixed="item.fixed"
      >
        <template #default="scope">
          <div v-if="item.prop == 'operation'">
            <el-button size="small" type="primary" @click="DialogVisible(scope.row)"
              >添加至任务中</el-button
            >
            <el-button size="small" type="primary" @click="primaryLook(scope.row)">检测</el-button>
            <el-button type="danger" size="small" @click="removePreparation(scope.$index)"
              >移除</el-button
            >
          </div>
          <div v-if="item.prop == 'home'">
            <el-link type="primary" @click="_blank_page(scope.row[item.prop])">{{
              scope.row[item.prop]
            }}</el-link>
          </div>
          <div v-else-if="item.prop == 'live_status'">
            <el-link v-if="scope.row[item.prop] == 1" type="primary">未开始</el-link>
            <el-link v-else type="success">直播中</el-link>
          </div>
          <div v-else>{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="centerDialogVisible"
      center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="submit wp-960 no-drag">
        <p class="title">- 添加直播任务 -</p>
        <el-form status-icon label-width="80px" class="demo-ruleForm">
          <el-form-item label="任务标题" prop="title">
            <el-input
              v-model="title"
              type="text"
              placeholder="请输入直播任务标题"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="主播名称" prop="title">
            <el-input
              v-model="nickname"
              type="text"
              placeholder="请输入主播名称"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="直播链接" prop="url">
            <el-input
              v-model="url"
              type="textarea"
              placeholder="请输入主播的直播间链接"
              autocomplete="off"
              clearable
              autosize
            ></el-input>
          </el-form-item>
          <el-form-item label="直播时长" prop="duration">
            <el-input
              v-model="duration2"
              type="number"
              placeholder="请输入直播时长（小时）"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="人气数量" prop="count">
            <el-input
              v-model="count"
              type="number"
              placeholder="请输入直播所需要的人气数量"
              autocomplete="off"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer no-drag">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addYinTask"> 确 认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="less">
.tablebox {
  table tbody {
    display: block;
    height: 200px;
    overflow-y: scroll;
  }

  table thead,
  tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}

.submit {
  // padding: 20px;
  .title {
    text-align: center;
    margin: 40px 0;
    color: #7b89f1;
    font-size: 24px;
  }
  /deep/button {
    width: 100%;
    margin: 10px 0;
  }
  /deep/.el-button + .el-button,
  .el-checkbox.is-bordered + .el-checkbox.is-bordered {
    margin-left: 0;
  }
  .to-get-url {
    font-size: 14px;
    text-align: right;
    // margin: -11px 0px 14px 0;
    color: #7b89f1;
  }
}

@media (max-width: 768px) {
  .submit {
    width: 90%;
    box-sizing: border-box;
  }
}
</style>
